<template>
    <pageTabelLayout>
      <template #pageHeader>
        <div class="search-form isheader" v-if="headerShow">
          <div>
            <a-form size="small" :model="pageData" layout="inline">
              <a-form-item label="设备编号" v-if="permissionStore.hasPermisson('ppzl.cx')">
                <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                  v-model="pageData.dropDownData" @press-enter="huiche" />
              </a-form-item>
            </a-form>
          </div>
          <div>
            <Toolbar class="gesture" :items="pageData.btnList" @add="addHandler" @del="deleteHandler"
              @select="selectHandler">
            </Toolbar>
          </div>
        </div>
        <div class="my-divisders">
          <a-divider orientation="center">
            <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
          </a-divider>
        </div>
      </template>
      <template #pageTabel>
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef"
            class="ag-theme-alpine" :rowData="table.dataList" :localeText="localeText1" :columnDefs="tc"></AgGridVuesCopys>
        </a-spin>
      </template>
      <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size @change="PageSize"
        @page-size-change="change1" style="justify-content: center" :page-size="size" :current="page" />
      <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
        :width="400" :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
        @cancel="pageData.showAdd = false">
        <template #title>
          {{ pageData.sideTitle }}
        </template>
        <div>
          <a-form ref="formRef" layout="horizontal" :model="dataForm">
            <a-form-item label-col-flex="80px" label="设备编号" field="equipmenCode"
              :rules="[{ required: true, message: '设备编号必填' }]" :validate-trigger="['change', 'blur']">
              <!-- <a-select popup-container="html"  class="bacClass" v-model="dataForm.equipmenCode"  :allowClear="true"
                            @focus="focusJt">
                              <a-option v-for="item in pageData.JtList" :value="item.machineCode">{{ item.machineCode }}</a-option>
                          </a-select> -->
              <a-select popup-container="html"  class="bacClass" v-model="dataForm.equipmenCode" :loading="loading1" :allowClear="true"
                @search="handleSearch1" :filter-option="false" allow-search @focus="focusSel1">
                <a-option v-for="item in pageData.JtList" :value="item.machineCode">{{
                  item.machineCode + ' —— ' + item.machineName
                }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="日保养" field="sunUpkeep" label-col-flex="80px">
              <a-select popup-container="html"  class="bacClass" v-model="dataForm.sunUpkeep" allow-clear allow-search @click="byClick(1)">
                <a-option v-for="item in byList1" :value="item.id + '-' + item.templateName">{{ item.templateName
                }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="周保养" field="weekUpkeep" label-col-flex="80px">
              <a-select popup-container="html"  class="bacClass" v-model="dataForm.weekUpkeep" allow-clear allow-search @click="byClick(2)">
                <a-option v-for="item in byList2" :value="item.id + '-' + item.templateName">{{ item.templateName
                }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="月保养" field="monthUpkeep" label-col-flex="80px">
              <a-select popup-container="html"  class="bacClass" v-model="dataForm.monthUpkeep" allow-clear allow-search @click="byClick(3)">
                <a-option v-for="item in byList3" :value="item.id + '-' + item.templateName">{{ item.templateName
                }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label-col-flex="80px" label="备注">
              <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                show-word-limit />
            </a-form-item>
          </a-form>
        </div>
      </a-drawer>
      <a-modal v-model:visible="visible" :width="300"  :hide-cancel="true" ok-text="关闭" @ok="visible = false">
        <template #title>
          明细
        </template>
        <div class="mxClass">
          <div v-for="item in mxList">{{item}}</div>
        </div>
      </a-modal>
    </pageTabelLayout>
  </template>
    
  <script lang="ts">
  import { post, get } from '@/api/http'
  import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { pagingList } from '@/api/paging'
  // 引入
  
  import { localeText } from '@/api/aggridZw'
  
  
  export default {
    name: 'TimeSetting',
  
    setup() {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)
  
      function doRefresh() {
        pageData.pageLoading = true
        post({
          url: 'temRepair/bindingTime/findBindingTimePage',
          data: {
            page: page.value,
            limit: size.value,
            equipmenCode: pageData.dropDownData,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
  
              // 查询方法改
  
              gridOption.value.setRowData(data.list)
  
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
  
      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '序号',
          key: 'num',
          dataIndex: 'num',
          width: 150,
        },
  
        {
          title: '设备编号',
          key: 'equipmenCode',
          dataIndex: 'equipmenCode',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '日保养',
          key: 'upkeepType',
          dataIndex: 'upkeepType',
          width: 100,
          slotName: 'upkeepType',
          fixed: 'right',
        },
        {
          title: '周保养',
          key: 'upkeepType1',
          dataIndex: 'upkeepType1',
          width: 100,
          slotName: 'upkeepType1',
          fixed: 'right',
        },
        {
          title: '月保养',
          key: 'upkeepType2',
          dataIndex: 'upkeepType2',
          width: 100,
          slotName: 'upkeepType2',
          fixed: 'right',
        },
        {
          title: '操作',
          key: 'id',
          slotName: 'act',
          width: 150,
          fixed: 'right',
        },
      ])
  
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
  
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `<a-tag class="tagCss" v-if="e"  @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                e: permissionStore.hasPermisson('bdsjsz.xg'),
                a,
              }
            },
          }
        }
        if (o.slotName === 'upkeepType') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                        <a-space>
                          <a-tag class="tagCss"  @click="b">{{a}}</a-tag>
                       </a-space>`,
            setup(props: any) {
              const b = () => {
                  byMxFun(props.params.data.sunUpkeep)
              }
              return {
                a: props.params.data.sunUpkeepName,
                b
              }
            },
          }
        }
        if (o.slotName === 'upkeepType1') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                          <a-space>
                            <a-tag class="tagCss"  @click="b">{{a}}</a-tag>
                       </a-space>`,
            setup(props: any) {
              const b = () => {
                byMxFun(props.params.data.weekUpkeep)
              }
              return {
                a: props.params.data.weekUpkeepName,
                b
              }
            },
          }
        }
        if (o.slotName === 'upkeepType2') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `
                          <a-space>
                            <a-tag class="tagCss"  @click="b">{{a}}</a-tag>
                       </a-space>`,
            setup(props: any) {
              const b = () => {
                byMxFun(props.params.data.monthUpkeep)
              }
              return {
                a: props.params.data.monthUpkeepName,
                b
              }
            },
          }
        }
  
        return obj
      })
  
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: any[]
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        upList: any[]
        JtList: any[]
      }>({
        nameList: [],
        showAdd: false,
        sideTitle: '新增',
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        upList: [],
        JtList: [],
      })
  
      interface gcType {
        id: any
        company: any
      }
  
      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({ brandName: '', deleteState: 0 })
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { brandName: value, deleteState: 0 }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }
  
      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'product/Brand/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            let dataList: any = []
            data.forEach(function (o: any) {
              dataList.push(o['brandName'])
            })
            pageData.nameList = dataList
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
  
      onMounted(() => { })
      let cxbl = ''
      //查询
      const selectHandler = () => {
        page.value = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        selCxAll1({ machineCode: '' })
        for (var key in dataForm) {
          dataForm[key] = null
        }
        dataForm['upkeepTypeTemp'] = []
  
        pageData.showAdd = true
        pageData.sideTitle = '新增'
      }
      const dataForm: any = reactive({
        equipmenCode: null,
        "upkeepType": "",
        "sunUpkeep": null,
        "sunUpkeepId": null,
        "weekUpkeep": null,
        "weekUpkeepId": null,
        "monthUpkeep": null,
        "monthUpkeepId": null,
        "sunUpkeepName": '',
        "weekUpkeepName": '',
        "monthUpkeepName": '',
        remark: ''
      })
  
      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
  
      let formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            // if (dataForm['upkeepTypeTemp'].length != 0) {
            //   dataForm['upkeepType'] = dataForm['upkeepTypeTemp'].join()
            // }
            if (!dataForm.sunUpkeep && !dataForm.weekUpkeep && !dataForm.monthUpkeep) {
              Message.error('至少选择一项保养')
              return false
            }
            let typeString = []
            if (dataForm.sunUpkeep != '' && dataForm.sunUpkeep != null) {
              typeString.push(1)
              dataForm.sunUpkeepId = dataForm.sunUpkeep.split('-')[0]
              dataForm.sunUpkeepName = dataForm.sunUpkeep.split('-')[1]
            } else {
              dataForm.sunUpkeepId = null
              dataForm.sunUpkeepName = ''
            }
            if (dataForm.weekUpkeep != '' && dataForm.weekUpkeep != null) {
              typeString.push(2)
              dataForm.weekUpkeepId = dataForm.weekUpkeep.split('-')[0]
              dataForm.weekUpkeepName = dataForm.weekUpkeep.split('-')[1]
            } else {
              dataForm.weekUpkeepId = null
              dataForm.weekUpkeepName = ''
            }
            if (dataForm.monthUpkeep != '' && dataForm.monthUpkeep != null) {
              typeString.push(3)
              dataForm.monthUpkeepId = dataForm.monthUpkeep.split('-')[0]
              dataForm.monthUpkeepName = dataForm.monthUpkeep.split('-')[1]
            } else {
              dataForm.monthUpkeepId = null
              dataForm.monthUpkeepName = ''
            }
  
            let upkeepTypeString = ''
            typeString.forEach((res: any) => {
              if (res != '' && res != 'null' && res != null) {
                upkeepTypeString = upkeepTypeString == '' ? res : (upkeepTypeString + ',' + res)
              }
            })
            dataForm.upkeepType = upkeepTypeString
            pageData.pageLoading = true
            if (pageData.sideTitle === '新增') {
              post({
                url: 'temRepair/bindingTime/saveBindingTime',
                data: [{
                  "upkeepType": dataForm.upkeepType,
                  "sunUpkeep": dataForm.sunUpkeepId,
                  "weekUpkeep": dataForm.weekUpkeepId,
                  "monthUpkeep": dataForm.monthUpkeepId,
                  "equipmenCode": dataForm.equipmenCode,
                  "sunUpkeepName": dataForm.sunUpkeepName,
                  "weekUpkeepName": dataForm.weekUpkeepName,
                  "monthUpkeepName": dataForm.monthUpkeepName,
                  remark: dataForm.remark
                }],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
  
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                })
                .finally(() => {
                  doRefresh()
                  pageData.pageLoading = false
                })
            } else {
              post({
                url: 'temRepair/bindingTime/updateBindingTime',
                data: [{
                  id: dataForm.id,
                  "upkeepType": dataForm.upkeepType,
                  "sunUpkeep": dataForm.sunUpkeepId,
                  "weekUpkeep": dataForm.weekUpkeepId,
                  "monthUpkeep": dataForm.monthUpkeepId,
                  "equipmenCode": dataForm.equipmenCode,
                  "sunUpkeepName": dataForm.sunUpkeepName,
                  "weekUpkeepName": dataForm.weekUpkeepName,
                  "monthUpkeepName": dataForm.monthUpkeepName,
                  remark: dataForm.remark
                }],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  doRefresh()
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
  
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'temRepair/bindingTime/deleteBindingTime',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
  
      // let curobj = null
      const editHandler = (record: any) => {
        // dataForm['upkeepTypeTemp'] = []
        // curobj = record
        selCxAll1({ machineCode: '' })
        for (let key in record) {
          dataForm[key] = record[key]
        }
        if (record.sunUpkeep != null && record.sunUpkeep != '') {
          dataForm['sunUpkeep'] = record.sunUpkeep + '-' + record.sunUpkeepName
        }
        if (record.weekUpkeep != null && record.weekUpkeep != '') {
          dataForm['weekUpkeep'] = record.weekUpkeep + '-' + record.weekUpkeepName
        }
        if (record.monthUpkeep != null && record.monthUpkeep != '') {
          dataForm['monthUpkeep'] = record.monthUpkeep + '-' + record.monthUpkeepName
        }
        //   '1,2,3'或'1' 转[1,2,3] [1]
        // if (dataForm['upkeepType'] != '' && dataForm['upkeepType'] != null) {
        //   if (dataForm['upkeepType'].indexOf(',') != -1) {
        //     dataForm['upkeepTypeTemp'] = dataForm['upkeepType'].split(',')
        //   } else {
        //     dataForm['upkeepTypeTemp'].push(dataForm['upkeepType'])
        //   }
        // }
        pageData.sideTitle = '修改'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
  
      //下拉数据
      const options1 = ref<any>(pageData.JtList)
      const loading1 = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { machineCode: value }
          loading.value = true
          selCxAll1(ob)
          options.value = pageData.JtList
          loading.value = false
        } else {
          options.value = []
        }
      }
  
      //下拉框查询 机器类型
      function selCxAll1(val: any) {
        post({
          url: 'aps/dwMachine/getFieldValue',
          data: val,
        }).then((res: any) => {
          if (res.code === 200) {
            pageData.JtList = res.data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
  
      //下拉框得到焦点
      const focusSel1 = () => {
        selCxAll1({ machineCode: '' })
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()
  
      if (permissionStore.hasPermisson('bdsjsz.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('bdsjsz.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('bdsjsz.sc')) {
        pageData.btnList.push('删除')
      }
  
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const huiche = () => {
        page.value = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)
      const localeText1: any = ref(localeText)
      //查保养项目 下拉框
      function focusUp() {
        get({
          url: 'temRepair/upkeep/selectUpkeep',
        }).then((res: any) => {
          if (res.code === 200) {
            pageData.upList = res.data.list
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      // 查机台
      function focusJt() {
        post({
          url: 'planSingle/machine/getFieldValueWms',
          data: {
            machineName: '',
            companyId: null,
          },
        }).then((res: any) => {
          if (res.code === 200) {
            pageData.JtList = res.data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
  
      const byList1: any = ref([])
  
      const byList2: any = ref([])
  
      const byList3: any = ref([])
  
      const byClick = (num: any) => {
        post({
          url: 'temRepair/upkeepTemplate/selectUpkeepTemplate',
          data: {
            templateType: num
          }
        }).then((res: any) => {
          if (num == 1) {
            byList1.value = res.data.list
          } else if (num == 2) {
            byList2.value = res.data.list
          } else if (num == 3) {
            byList3.value = res.data.list
          }
        })
      }
  
      const visible = ref(false)
      const mxList:any = ref([])
      function byMxFun(num:any){
         post({
          url:'temRepair/upkeepTemplate/findUpkeepTemplateId',
          data:{
            id:Number(num)
          }
         }).then((res:any)=>{
          if(res.code == 200){
            mxList.value = res.data.list.upkeepTemplateDetailedList.map((res2:any)=>{
                 return res2.upkeepName
            })
            visible.value = true
          }
         })
      }
      return {
        mxList,
        visible,
        byList1,
        byList2,
        byList3,
        byClick,
        focusJt,
        focusUp,
        pagingList1,
        huiche,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        isChiese,
        options,
        loading,
        handleSearch,
        focusSel,
        options1,
        loading1,
        handleSearch1,
        focusSel1,
        headerShow,
        handleChange,
        gridReady,
        permissionStore,
      }
    },
    components: { Toolbar, PageTabelLayout,  },
  }
  </script>
  <style lang="less" scoped>
  .mxClass{
    width: 100%;
    div{
      width: 100%;
      text-align: center;
      height: 50px;
      font-family: Microsoft Yahei;
      font-weight: 600;
      font-size: 16px;
    }
  }
  </style>
    